package com.example.twoeightgang;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.provider.ContactsContract;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import org.w3c.dom.Text;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    private SoundPlayer soundPlayer;
    private String TAG="main";
    private CoinDateOpenHelper coinDateOpenHelper;
    private String PLAY_TABLE="player";
    private String PLAY_NAME="playname";
    private HashMap hashMap1;
    private HashMap hashMap2;
    private Handler handler=null; //此处创建于主线程中便于更新UI
    private Button btnStart;
    private Button btnEnding;
    private Button btnGuize;
    private Button btnYazhu;
    private Button btnSettings;
    private StartGame startGame;
    private ImageView beiban_1_a_v;
    private ImageView beiban_1_b_v;
    private ImageView beiban_2_a_v;
    private ImageView beiban_2_b_v;
    private ImageView beiban_3_a_v;
    private ImageView beiban_3_b_v;
    private ImageView beiban_4_a_v;
    private ImageView beiban_4_b_v;
    private ImageView beiban_5_a_v;
    private TextView winner1;
    private TextView winner2;
    private TextView winner3;
    private TextView winner4;
    private TextView jingbi1;
    private TextView jingbi2;
    private TextView jingbi3;
    private TextView jingbi4;
    TextView yazhuxianshi;
    String jingbiNum;
    String danzhangPK_1_a;
    String danzhangPK_1_b;
    String danzhangPK_2_a;
    String danzhangPK_2_b;
    String danzhangPK_3_a;
    String danzhangPK_3_b;
    String danzhangPK_4_a;
    String danzhangPK_4_b;
    String danzhangPK_5_a;
    int danzhangPK_1_a_num;
    int danzhangPK_1_b_num;
    int danzhangPK_2_a_num;
    int danzhangPK_2_b_num;
    int danzhangPK_3_a_num;
    int danzhangPK_3_b_num;
    int danzhangPK_4_a_num;
    int danzhangPK_4_b_num;
    int danzhangPK_5_a_num;
    int index;
    private  boolean one_ba;
    private  boolean two_ba;
    private  boolean three_ba;
    private  boolean four_ba;
    ImageView[] imageViews;
    public static int coin1=10000;
    public static int coin2=10000;
    public static int coin3=10000;
    public static int coin4=10000;
    public static int yazhu=10;
    private static boolean isfirst=true;
    private String playname="";
    private SQLiteDatabase coinDate;//=coinDateOpenHelper.getWritableDatabase();
    static int totalnumber=0;
    Intent intentMusic;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //View view = View.inflate(this, R.layout.activity_main, null);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN
                ,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        handler=new Handler();
        startGame=new StartGame();
        coinDateOpenHelper=new CoinDateOpenHelper(this,1);
        coinDate=coinDateOpenHelper.getWritableDatabase();
        btnStart=(Button)findViewById(R.id.start_fapai);
        btnEnding=(Button)findViewById(R.id.ending_open);
        btnGuize=(Button)findViewById(R.id.guize);
        btnYazhu=(Button)findViewById(R.id.yazhu);
        btnSettings=(Button)findViewById(R.id.new_settings);
        beiban_1_a_v=(ImageView)findViewById(R.id.beiban_1_a);
        beiban_1_b_v=(ImageView)findViewById(R.id.beiban_1_b);
        beiban_2_a_v=(ImageView)findViewById(R.id.beiban_2_a);
        beiban_2_b_v=(ImageView)findViewById(R.id.beiban_2_b);
        beiban_3_a_v=(ImageView)findViewById(R.id.beiban_3_a);
        beiban_3_b_v=(ImageView)findViewById(R.id.beiban_3_b);
        beiban_4_a_v=(ImageView)findViewById(R.id.beiban_4_a);
        beiban_4_b_v=(ImageView)findViewById(R.id.beiban_4_b);
        beiban_5_a_v=(ImageView)findViewById(R.id.beiban_5_a);
        jingbi1=(TextView)findViewById(R.id.jingbi1);
        jingbi2=(TextView)findViewById(R.id.jingbi2);
        jingbi3=(TextView)findViewById(R.id.jingbi3);
        jingbi4=(TextView)findViewById(R.id.jingbi4);
        yazhuxianshi=(TextView)findViewById(R.id.yazhuxianshi);
        winner1=(TextView)findViewById(R.id.winner_or_loser_1);
        winner2=(TextView)findViewById(R.id.winner_or_loser_2);
        winner3=(TextView)findViewById(R.id.winner_or_loser_3);
        winner4=(TextView)findViewById(R.id.winner_or_loser_4);
        imageViews=new ImageView[8];
        one_ba=false;
        two_ba=false;
        //three_ba=false;
        four_ba=false;
        init();
//        hashMap1 =new HashMap();
//        hashMap2 =new HashMap();
        for(int i=0;i<=8;i++){
//            hashMap1.put(i , startGame.getDanzhang(i));
            Log.d("kaikai","danzhangPK_"+ i + "_a == " + startGame.getDanzhang(i));
            Log.d("kaikai","danzhangPK_"+ i + "_a_num == " + startGame.getDanzhangNum(i));
        }
        btnGuize.setOnClickListener(this);
        btnYazhu.setOnClickListener(this);
        btnSettings.setOnClickListener(this);
        btnStart.setOnClickListener(this);
        btnEnding.setOnClickListener(this);
        intentMusic=new Intent();
        intentMusic.setClass(this,MusicService.class);
        startService(intentMusic);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main,menu);
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK) {
            MyBaocunDialog myBaocunDialog=new MyBaocunDialog(this,playname);
            myBaocunDialog.setView(new EditText(this));
            myBaocunDialog.show();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG,"onStart");
    }


    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG,"onResume");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d(TAG,"onRestart");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG,"onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG,"onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBroadcastReceiver);
        stopService(intentMusic);
        Log.d(TAG,"onDestroy");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.start_fapai:
                init();
                for(int i=0;i<=8;i++){
//            hashMap1.put(i , startGame.getDanzhang(i));
                    Log.d("ykk","danzhangPK_"+ i + "_a == " + startGame.getDanzhang(i));
                    Log.d("ykk","danzhangPK_"+ i + "_a_num == " + startGame.getDanzhangNum(i));
                }
                startFapai(whoStart());
                Log.d("ykk","whostart == " + whoStart());
                pKVisiable();
                isfirst=false;
                break;
            case R.id.ending_open:
                if(!isfirst) {
                    whoStart(whoStart());
                    whoWin();
                }
                isfirst=true;
                break;
            case R.id.guize:
                Intent intent=new Intent();
                intent.setClass(this,GuizeActivity.class);
                startActivity(intent);
                break;
            case R.id.yazhu:
                MyDialog builder = new MyDialog(MainActivity.this,yazhu);
                builder.setView(new EditText(this));
                builder.show();
                break;
            case R.id.new_settings:
                Intent intent1=new Intent();
                intent1.setClass(MainActivity.this,SettingsActivity.class);
                intent1.putExtra("username",playname);
                Log.d("uuuu","playname = " + playname);
                startActivity(intent1);
                break;
                default:
                    break;
        }
    }

    private void insertCoin(){
//        SQLiteDatabase coinDate=coinDateOpenHelper.getWritableDatabase();
        ContentValues values=new ContentValues();
        values.put("id",1);
        values.put("name","player1");
        values.put("num",coin1);
        coinDate.insert(PLAY_TABLE,null,values);
        values.clear();
        values.put("id",2);
        values.put("name","player2");
        values.put("num",coin2);
        coinDate.insert(PLAY_TABLE,null,values);
        values.clear();
        values.put("id",3);
        values.put("name","player3");
        values.put("num",coin3);
        coinDate.insert(PLAY_TABLE,null,values);
        values.clear();
        values.put("id",4);
        values.put("name","player4");
        values.put("num",coin4);
        coinDate.insert(PLAY_TABLE,null,values);
    }
    private void updateCoin(){
//        SQLiteDatabase coinDate=coinDateOpenHelper.getWritableDatabase();
        ContentValues values=new ContentValues();
        values.put("num",coin1);
        coinDate.update(PLAY_TABLE,values,"name=?",new String[]{"player1"});
        values.clear();
        values.put("num",coin2);
        coinDate.update(PLAY_TABLE,values,"name=?",new String[]{"player2"});
        values.clear();
        values.put("num",coin3);
        coinDate.update(PLAY_TABLE,values,"name=?",new String[]{"player3"});
        values.clear();
        values.put("num",coin4);
        coinDate.update(PLAY_TABLE,values,"name=?",new String[]{"player4"});
    }


    private int getNum(int a){
//        SQLiteDatabase coinDate=coinDateOpenHelper.getWritableDatabase();
        Cursor cursor=coinDate.rawQuery("select * from player where id=?",new String[]{a+""});
        Log.d("ykk","coinDate:" + coinDate + "  cursor = " + cursor);
        if(cursor!=null) {
            if (cursor.moveToFirst()) {
                int total = cursor.getInt(cursor.getColumnIndex("num"));
                Log.d("ykk", "total:" + total);
                return total;
            }
        }
        cursor.close();
        return 0;
    }



    private int getDrawableID(String imageName){
        try {
            Field field=R.drawable.class.getField(imageName);
            return Integer.parseInt(field.get(null).toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public void init(){
        startGame.init();
        SoundPlayer.init(this);
        sharedPreferences=getSharedPreferences("config",MODE_PRIVATE);
        editor=sharedPreferences.edit();
        boolean fristload = sharedPreferences.getBoolean("isfirstboot", true);
        if(fristload) {
            coin1=10000;
            coin2=10000;
            coin3=10000;
            coin4=10000;
            editor.putBoolean("isfirstboot", false);
            editor.commit();
        }else{
            coin1=getNum(1);
            coin2=getNum(2);
            coin3=getNum(3);
            coin4=getNum(4);
        }
        registerBoradcastReceiver();

        Log.d(TAG,"111== " + coin1);
        insertCoin();
        jingbi1.setText(coin1+"");
        jingbi2.setText(coin2+"");
        jingbi3.setText(coin3+"");
        jingbi4.setText(coin4+"");
        yazhuxianshi.setText(yazhu+"");
        winner1.setVisibility(View.INVISIBLE);
        winner2.setVisibility(View.INVISIBLE);
        winner3.setVisibility(View.INVISIBLE);
        winner4.setVisibility(View.INVISIBLE);
        imageViews[0]=beiban_1_a_v;
        imageViews[1]=beiban_1_b_v;
        imageViews[2]=beiban_2_a_v;
        imageViews[3]=beiban_2_b_v;
        imageViews[4]=beiban_3_a_v;
        imageViews[5]=beiban_3_b_v;
        imageViews[6]=beiban_4_a_v;
        imageViews[7]=beiban_4_b_v;
        danzhangPK_1_a=startGame.getDanzhang(0);
        danzhangPK_1_b=startGame.getDanzhang(1);
        danzhangPK_2_a=startGame.getDanzhang(2);
        danzhangPK_2_b=startGame.getDanzhang(3);
        danzhangPK_3_a=startGame.getDanzhang(4);
        danzhangPK_3_b=startGame.getDanzhang(5);
        danzhangPK_4_a=startGame.getDanzhang(6);
        danzhangPK_4_b=startGame.getDanzhang(7);
        danzhangPK_5_a=startGame.getDanzhang(8);
        danzhangPK_1_a_num=startGame.getDanzhangNum(0);
        danzhangPK_1_b_num=startGame.getDanzhangNum(1);
        danzhangPK_2_a_num=startGame.getDanzhangNum(2);
        danzhangPK_2_b_num=startGame.getDanzhangNum(3);
        danzhangPK_3_a_num=startGame.getDanzhangNum(4);
        danzhangPK_3_b_num=startGame.getDanzhangNum(5);
        danzhangPK_4_a_num=startGame.getDanzhangNum(6);
        danzhangPK_4_b_num=startGame.getDanzhangNum(7);
        danzhangPK_5_a_num=startGame.getDanzhangNum(8);

    }

    private BroadcastReceiver  mBroadcastReceiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(action.equals("com.ykk.change")){
                yazhuxianshi.setText(yazhu + "");
            }else if(action.equals("com.ykk.baocun")){
                String player_new = intent.getStringExtra("yaner");
                baocun(player_new);
//                finish();
            }else if(action.equals("com.ykk.baocunnoexit")){
                String player_new = intent.getStringExtra("yaner");
                baocunNoexit(player_new);
            }
        }

    };

    private void registerBoradcastReceiver(){
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction("com.ykk.change");
        myIntentFilter.addAction("com.ykk.baocun");
        myIntentFilter.addAction("com.ykk.baocunnoexit");
        //注册广播
        registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    public void whoWin(){
        one_ba= suanfa(danzhangPK_3_a_num,danzhangPK_3_b_num,danzhangPK_1_a_num,danzhangPK_1_b_num);
        two_ba= suanfa(danzhangPK_3_a_num,danzhangPK_3_b_num,danzhangPK_2_a_num,danzhangPK_2_b_num);
        four_ba= suanfa(danzhangPK_3_a_num,danzhangPK_3_b_num,danzhangPK_4_a_num,danzhangPK_4_b_num);
        Log.d("ykk","one_ba == " + one_ba + "  two_ba == " + two_ba + "  four_ba == " + four_ba);
        if(!one_ba){
            winner1.setVisibility(View.VISIBLE);
            winner1.setText(R.string.win);
            winner1.setTextColor(getResources().getColor(R.color.colorRed));
            coin1+=yazhu;
            coin3-=yazhu;

        }else{
            winner1.setVisibility(View.VISIBLE);
            winner1.setText(R.string.lose);
            winner1.setTextColor(getResources().getColor(R.color.colorBlue));
            coin1-=yazhu;
            coin3+=yazhu;
        }
        if(!two_ba){
            winner2.setVisibility(View.VISIBLE);
            winner2.setText(R.string.win);
            winner2.setTextColor(getResources().getColor(R.color.colorRed));
            coin2+=yazhu;
            coin3-=yazhu;
        }else{
            winner2.setVisibility(View.VISIBLE);
            winner2.setText(R.string.lose);
            winner2.setTextColor(getResources().getColor(R.color.colorBlue));
            coin2-=yazhu;
            coin3+=yazhu;
        }
        if(!four_ba){
            winner4.setVisibility(View.VISIBLE);
            winner4.setText(R.string.win);
            winner4.setTextColor(getResources().getColor(R.color.colorRed));
            coin4+=yazhu;
            coin3-=yazhu;
        }else{
            winner4.setVisibility(View.VISIBLE);
            winner4.setText(R.string.lose);
            winner4.setTextColor(getResources().getColor(R.color.colorBlue));
            coin4-=yazhu;
            coin3+=yazhu;
        }
        jingbi1.setText(coin1+"");
        jingbi2.setText(coin2+"");
        jingbi3.setText(coin3+"");
        jingbi4.setText(coin4+"");
        updateCoin();
    }

    public boolean suanfa(int a,int b,int c,int d){
        boolean isVis=true;
        if(((a+b)%10) > ((c+d)%10)) {
            if (c == d && a != b) {
                Log.d("ykk", "111 a==" + a + " b==" + b + " c==" + c + " d==" + d);
                isVis = false;
                //return isVis;
            } else if (a == b && c == d && a < c) {
                Log.d("ykk", "222 a==" + a + " b==" + b + " c==" + c + " d==" + d);
                isVis = false;
                //return isVis;
            } else if ((c == 2 && d == 8) || (c == 8 && d == 2) && a != b) {
                Log.d("ykk", "333 a==" + a + " b==" + b + " c==" + c + " d==" + d);
                isVis = false;
                //return isVis;
            } else {
                Log.d("ykk", "444 a==" + a + " b==" + b + " c==" + c + " d==" + d);
                isVis = true;
            }
        }else if (((a+b)%10) == ((c+d)%10)){
            int max=0;
            List<Integer> nums = new ArrayList<Integer>();
            nums.add(a);
            nums.add(b);
            nums.add(c);
            nums.add(d);
            max= Collections.max(nums);
            if(max==a||max==b){
                isVis=true;
            }else{
                isVis=false;
            }
        }else if ((c == 2 && d == 8) || (c == 8 && d == 2) && a != b){
            isVis=true;
        }else{
            Log.d("ykk","555 a==" + a + " b==" + b+" c==" + c + " d==" + d);
            isVis=false;
            //return isVis;
        }
        return isVis;
    }

    public void whoStart(int val){
        if(val==1){
            for(int i=0;i<imageViews.length;i++){
                imageViews[i].setImageResource(getDrawable(startGame.getDanzhang(i)));
            }
        }else if(val==2){
            for(int i=2,j=1;i<imageViews.length+2;i++){
                if(i>=imageViews.length){
                    i=i-imageViews.length;
                }
                if(j>8){
                    break;
                }
                imageViews[i].setImageResource(getDrawable(startGame.getDanzhang(i)));
                Log.d("ykk","imageViews == " + i + "  ss = " + imageViews[i] + "/n  startGame.getDanzhang(i) == " + startGame.getDanzhang(i));
                j++;
            }
        }else if (val==3){
            for(int i=3,j=1;i<imageViews.length+3;i++){
                if(i>=imageViews.length){
                    i=i-imageViews.length;
                }
                if(j>8){
                    break;
                }
                imageViews[i].setImageResource(getDrawable(startGame.getDanzhang(i)));
                j++;
            }
        }else if (val == 0 ){
            for(int i=4,j=1;i<imageViews.length+4;i++){
                if(i>=imageViews.length){
                    i=i-imageViews.length;
                }
                if(j>8){
                    break;
                }
                imageViews[i].setImageResource(getDrawable(startGame.getDanzhang(i)));
                j++;
            }
        }
    }

    public void pKVisiable(){
        for(int i=0;i<imageViews.length;i++){
            Log.d("ykk","i == " + i + " imageViews[i] " + imageViews[i]);
            imageViews[i].setImageResource(R.drawable.pk_back);
            imageViews[i].setVisibility(View.VISIBLE);
        }
    }

    public int whoStart(){
        return (danzhangPK_5_a_num+2)%4;
    }

    private TranslateAnimation translateAnimation=null;

    public void showAnimation(){
        translateAnimation=new TranslateAnimation(-200,0,-200,0);
        translateAnimation.setDuration(1000);
        beiban_5_a_v.setImageResource(R.drawable.weixin);
    }

    public synchronized  void startFapai(int i){
        new Thread() {
            @Override
            public void run() {
                try {
                    handler.post(runnable); //在子线程的run方法中向UI线程post，runnable对象来更新UI。
                    sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }

    Runnable runnable=new Runnable() { //构建Runnable对象，在Runnable中更新界面。
        @Override
        public void run() {
            showAnimation();
            beiban_5_a_v.setAnimation(translateAnimation);
            beiban_5_a_v.setImageResource(getDrawable(danzhangPK_5_a));
            beiban_5_a_v.setVisibility(View.VISIBLE);
        }
    };
    

    public int getDrawable(String s){
        index = this.getResources().getIdentifier(s, "drawable", getPackageName());
        return index;
    }

    public void baocun(String playname1){
        baocunNoexit(playname1);
        finish();
    }


    public void baocunNoexit(String playname1){
//        SQLiteDatabase coinDate=coinDateOpenHelper.getWritableDatabase();
        ContentValues values=new ContentValues();
        //values.put("id",1);
        values.put("name",playname1);
        values.put("num",coin3);
        Log.d("ykk","name == " + playname1 + "  num == " + coin3);
        coinDate.insert(PLAY_NAME,null,values);
//        editor=sharedPreferences.edit();
//        editor.putBoolean("isfirstboot", false);
//        editor.commit();
        coin1=10000;
        coin2=10000;
        coin3=10000;
        coin4=10000;
        jingbi1.setText(coin1+"");
        jingbi2.setText(coin2+"");
        jingbi3.setText(coin3+"");
        jingbi4.setText(coin4+"");
        updateCoin();
        pKVisiable();
        beiban_5_a_v.setImageResource(R.drawable.pk_back);
        isfirst=true;
        winner1.setVisibility(View.INVISIBLE);
        winner2.setVisibility(View.INVISIBLE);
        winner3.setVisibility(View.INVISIBLE);
        winner4.setVisibility(View.INVISIBLE);
    }

}
